<?php

namespace app\api\controller;

use app\api\server\Order as ServerOrder;
use app\api\server\User as ServerUser;
use app\common\controller\Api;
use app\common\model\Circulation;
use app\common\model\FounLog;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\order\Order;
use app\common\model\User;
use app\common\model\UserGroup;
use think\Db;

/**
 * 定时任务
 */
class Crontab extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    //  MoneyLog::commission($order);
    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (结算分佣)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function settlement_commission()
    {

        Db::startTrans();
        try {
            $auto_settlement = config('site.auto_settlement');
            $settletime = time() - $auto_settlement * 86400;
            $orders = Order::whereTime('paytime', '<', $settletime)->where(['order_status' => '30', 'is_settle' => '0'])->select();
            if ($orders) {
                MoneyLog::commission($orders);
                foreach ($orders as $order) {
                    ServerOrder::add_fund_account_details($order);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }

    /**
     * @Author LK
     * @date: 2024-01-15 
     * @ApiTitle (共享金自动兑换)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function auto_convertibility()
    {
        $time = time();
        $users = User::where('tg_gold|xf_gold', '>', 0)->select();
        if (!$users) {
            return 'success';
        }
        $position_scale = config('site.position_scale');
        $position_scale = bcdiv($position_scale, 100, 2);
        if ($position_scale <= 0) {
            return 'success';
        }
        Db::startTrans();
        try {
            foreach ($users as $k => $v) {
                //推广共享金自动兑换
                if ($v->tg_gold >= 1 && $v->tgexpiretime >= $time) {
                    if ($v->tg_gold > 0 && $$v->tg_gold < 1) {
                        $tg_gold = $v->tg_gold;
                    } else {
                        $tg_gold = $v->tg_gold * $position_scale;
                    }
                    if ($tg_gold <= 0) {
                        continue;
                    }
                    if (GoldLog::where(['type' => 1, 'class' => 2, 'user_id' => $v->id])->whereTime('createtime', 'today')->find()) {
                        continue;
                    }
                    ServerUser::exchangegold(['num' => $tg_gold, 'type' => 1, 'user_id' => $v->id, 'msg' => '自动兑换']);
                    //刷新倒计时
                    $v->tgexpiretime = bcadd($time, config('site.countdown') * 86400);
                }
                //个人共享金自动兑换
                if ($v->xf_gold >= 1 && $v->xfexpiretime >= $time) {
                    if ($v->xf_gold > 0 && $$v->xf_gold < 1) {
                        $xf_gold = $v->xf_gold;
                    } else {
                        $xf_gold = $v->xf_gold * $position_scale;
                    }
                    if ($xf_gold <= 0) {
                        continue;
                    }
                    if (GoldLog::where(['type' => 2, 'class' => 2, 'user_id' => $v->id])->whereTime('createtime', 'today')->find()) {
                        continue;
                    }
                    ServerUser::exchangegold(['num' => $xf_gold, 'type' => 2, 'user_id' => $v->id, 'msg' => '自动兑换']);
                    //刷新倒计时
                    $v->xfexpiretime = bcadd($time, config('site.countdown') * 86400);
                }
                $v->save();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
    /**
     * @Author LK
     * @date: 2024-01-03 
     * @ApiTitle (共享金实时价格结算 日结)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function price_settlement()
    {
        $foun = FounLog::order('id desc')->value('after') ?? 0;
        $check = Circulation::whereTime('date', 'today')->count();
      
        if ($check) {
            return 'success';
        }
        Db::startTrans();
        try {
            $golds = User::field('sum(tg_gold) as tggold,sum(xf_gold) as xfgold')->find();
            $gold = $golds['tggold'] + $golds['xfgold'];
            if ($gold <= 0) {
                $money = 0;
            } else {
                $money = bcdiv($foun, $gold, 2);
                if ($money <= 0) {
                    $money = 0;
                }
                //共享金膨胀
                $dilate_limit = config('site.dilate_limit');
                if ($dilate_limit > 0 && $money >= $dilate_limit) {
                    $users = User::where('tg_gold|xf_gold', '>', 0)->select();
                    foreach ($users as $v) {
                        if ($v->tg_gold > 0) {
                            $tg_gold = bcmul($v->tg_gold, $dilate_limit, 5);
                            User::gold(1, bcsub($tg_gold, $v->tg_gold, 5), $v->id, '膨胀所得(推广)');
                            $v->tg_gold = $tg_gold;
                        }
                        if ($v->xf_gold > 0) {
                            $xf_gold = bcmul($v->xf_gold, $dilate_limit, 5);
                            User::gold(2,  bcsub($xf_gold, $v->xf_gold, 5), $v->id, '膨胀所得(个人)');
                            $v->xf_gold = $xf_gold;
                        }
                        $v->save();
                    }
                    $money = 1;
                }
            }
            Circulation::create([
                'date' => date('Y-m-d'),
                'circulation' => $money,
                'foun' => $foun,
                'contributory' => $gold,
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }




    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (自动收货)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function auto_take()
    {
        Db::startTrans();
        try {
            $order = Order::all(['order_status' => '20']);
            $auto_take_day = config('site.auto_take_day');
            if ($auto_take_day > 0) {
                $take_time = bcmul($auto_take_day, 86400, 0);
            } else {
                $take_time = 0;
            }
            $time = time();
            if ($order) {
                foreach ($order as $k => $v) {
                    if ($take_time > 0 && $v->sendtime + $take_time > $time) {
                        continue;
                    }
                    $v->taketime = time();
                    $v->order_status = '30';
                    $v->save();
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }

    /**
     * @Author LK
     * @date: 2023-10-20 
     * @ApiTitle (身份升级)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function identity_upgrade()
    {
        Db::startTrans();
        try {
            $users = User::where('group_id', '>', 1)->select();
            if (!$users) {
                return 'success';
            }
            foreach ($users as $k => $v) {
                $group = UserGroup::get($v->group_id + 1);
                //升级条件关闭，直接跳过
                if (!$group) {
                    continue;
                }
                if ($group->status == 'hidden') {
                    continue;
                }
                if (in_array($v->group_id, [3, 4])) {
                    $uids = User::where("find_in_set(:id,parent_ids)", ['id' => $v->id])->column('id');
                    $total_fee = Order::whereIn('user_id', $uids)->where('is_settle', 1)->where('order_status', '>', '0')->sum('pay_fee');
                    if ($total_fee >= $group->team_performance) {
                        $v->group_id = $v->group_id + 1;
                        $v->save();
                    }
                }
                if ($v->group_id > 4) {
                    $uids = User::where(['pid' => $v->id])->column('id');
                    $total = 0;
                    $max = 0;
                    foreach ($uids as  $vv) {
                        $user_ids = User::where("find_in_set(:id,parent_ids)", ['id' => $vv])->column('id');
                        $totalnum = Order::whereIn('user_id', $user_ids)->where('is_settle', 1)->where('order_status', '>', '0')->sum('pay_fee');
                        $total += $totalnum;
                        if ($max < $totalnum) {
                            $max = $totalnum;
                        }
                    }
                    $yj = bcsub($total, $max, 2);
                    if ($yj >= $group->team_performance) {
                        $v->group_id = $v->group_id + 1;
                        $v->save();
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
}
